<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Tools\Func;
use App\Models\AdminUser;
use App\Models\Jiuzhenren;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\DB;

use App\Imports\FeiYongImport;

class UserController extends Controller
{
    use Func;

    public function login(Request $request)
    {

        if (!$username = trim($request->username) ?? '') {
            return $this->returnJson(1, '账号不能为空', $request->all());    
        }
            if (!$password = trim($request->password) ?? '') {
            return $this->returnJson(1, '密码不能为空', $request->all());    
        }

        if (!$user = AdminUser::where([
                'admin_name' => $username,
                'password' => $password
            ])->first()) {
            return $this->returnJson(1, '账号密码错误', $request->all());  
        }

        return $this->returnJson(0, 'success', $user);

    }

	public function getJiuzhenren(Request $request)
	{
		$data = Jiuzhenren::get();
		return $this->returnJson(0, 'success', $data);
	}
	
	public function list(Request $request)
	{
	    $data = AdminUser::orderBy('id', 'asc')->paginate($request->limit ?? 10);
	    return $this->returnJson(0, 'success', $data);
	}
	
	// 添加管理员
	public function add(Request $request)
	{
		if (!AdminUser::create([
			'admin_name' => $request->admin_name,
			'password' => $request->password,
			'keshi' => $string = implode(',', $request->checkedValue),
			'created_at' => date('Y-m-d H:i:s')
		])) {
	        return $this->returnJson(1, '添加失败');
	    }
	
	    return $this->returnJson(0, '添加成功');
	}

    // 删除
    public function del(Request $request)
    {
        if (!AdminUser::where('id', $request->id)->delete()) {
            return $this->returnJson(1, '删除失败');
        }

        return $this->returnJson(0, '删除成功');
    }
	
	// 获得
	public function get(Request $request)
	{
		// dump($request->all());exit;
	    $res = AdminUser::where('id', $request->id)->first();
		$res->checkedValue = explode(',', $res->keshi);
	    return $this->returnJson(0, 'success', $res);
	}
	
	// 编辑
	public function edit(Request $request)
	{
	    // dd($request->addAccount);
	    if (!$res = AdminUser::where('id', $request->id)->update([
			'admin_name' => $request->admin_name,
			'password' => $request->password,
			'keshi' => $string = implode(',', $request->checkedValue),		
	    ])) {
	        return $this->returnJson(1, '修改失败', $res);
	    }
	
	    return $this->returnJson(0, '修改成功', $res);       
	}
}
